package controllers

import (
	"encoding/json"
	"map/models"
)

type ConfigController struct {
	BaseController
}

func (this *ConfigController) Info() {
	result, _ := models.ConfigAllList()
	list := make([]map[string]interface{}, len(result))
	var f interface{}
	for k, v := range result {
		row := make(map[string]interface{})
		row["describe"] = v.Describe
		row["field"] = v.Field
		row["type"] = v.Type
		row["value"] = v.Value
		if v.Type == 1 {
			err := json.Unmarshal([]byte(v.Value), &f)
			if err == nil {
				row["value"] = f
			}
		}
		list[k] = row
	}
	this.successData("", list)
}

func (this *ConfigController) Update() {
	result, _ := models.ConfigAllList()
	for _, v := range result {
		if this.GetString(v.Field) == "" {
			continue
		}
		if v.Type == 0 {
			models.ConfigValueByField(v.Field, this.GetString(v.Field))
		} else if v.Type == 1 {
			b, err := json.Marshal(this.GetStrings(v.Field))
			if err == nil {
				models.ConfigValueByField(v.Field, string(b))
			}
		}
	}
	this.success("")
}
